package linklist;

import org.junit.Test;

import java.util.HashMap;

/**
 * @author kunkun
 * @className LeetCode_143
 * @Description 重排链表
 * @date 2025/3/12 10:23
 */
public class LeetCode_143 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public void reorderList(ListNode head) {
        solution(head);
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        node1.next = null;
//        ListNode node2 = new ListNode(2);
//        ListNode node3 = new ListNode(3);
//        ListNode node4 = new ListNode(4);
//        ListNode node5 = new ListNode(5);
//        node1.next=node2;
//        node2.next=node3;
//        node3.next=node4;
//        node4.next=node5;
        reorderList(node1);
        while(node1!=null){
            System.out.print(node1.val+" ");
            node1=node1.next;
        }
    }


    public void solution(ListNode head){
        //1.计算长度
        int length=0;
        ListNode temp = head;
        while (temp!=null){
            length++;
            temp=temp.next;
        }
        if (length==1){
            return;
        }

        //2.反转
        int start  =  (length%2==0)?length/2+1:length/2+2;  //反转起始位置
        temp = head;
        for (int i = 0; i < start-2; i++) {
            temp = temp.next;
        }
        ListNode list2 = reverseList(temp.next);
        temp.next = null;

        ListNode tempList = list2;
        while (tempList!=null){
            tempList= tempList.next;
        }

        //3.归并
        while(list2!=null){
            ListNode temp2 = head.next;
            ListNode temp3 = list2.next;
            head.next=list2;
            list2.next=temp2;
            list2=temp3;
            head=temp2;
        }

    }

    //链表反转
    public ListNode reverseList(ListNode head){
        ListNode fast = head.next;
        ListNode slow = head;
        slow.next=null;
        while(fast!=null){
            ListNode temp = fast.next;
            fast.next = slow;
            slow=fast;
            fast=temp;
        }
        return slow;
    }

}
